import React, { useState, useEffect, useRef, useContext, useReducer } from "react"
import { TestContext } from '../Context'

const reducer = (state, action) => {
    // action: 是个对象，其中必须要有的参数为type
    if(action.type === 'CHANGE_USER_INFO') {
        return {
            ...state,
            userInfo: {
                ...state.userInfo,
                name: action.data
            }
        }
    }
    return state
}

const initState =  {
    userInfo: {
        name: '张三',
        sex: '男',
        age: '15'
    }
}

const Fun = () => {
    const [num, setNum] = useState('') 

    const [newNum, setnewNum] = useState(0)

    const inputRef = useRef();

    const { name, title } = useContext(TestContext)

    const [state, dispatch] = useReducer(reducer, initState)

    useEffect(() => {
        // 如果第二个参数为一个空数组  模拟生命周期 componentDidMount()
        // 如果第二个参数不传，模拟生命周期 componentDidUpdate()
        console.log('更新后', name, title)
    }, [])

    useEffect(() => {
        console.log(num)
    }, [newNum, num])

    const getInputValue = () => {
        console.log(inputRef.current.value)
    }

    return <div>
        步进器：
        <div>
            {/* 如果表单组件绑定了value 值，表单组件会变成受控组件 */}
            {/* 没有绑定value的form表单元素  被称为非受控组件 */}
            <input  ref={inputRef} type="text" />
            <button onClick={() => getInputValue()}>搜索</button>
            <button onClick={() => setnewNum(newNum - 1)}>-</button>
            <span>{newNum}</span>
            <button onClick={() => setnewNum(newNum  + 1)}>+</button>

            <div>
                <h3>用户信息：</h3>
                <div>
                    <span>姓名：{state.userInfo.name}</span>
                    <button onClick={() => dispatch({type: 'CHANGE_USER_INFO', data: '李四'})}>改变</button>
                </div>
                <div>
                    <span>性别：{state.userInfo.sex}</span>
                </div>
                <div>
                    <span>年龄：{state.userInfo.age}</span>
                </div>
            </div>
        </div>
    </div>
}

export default Fun